package com.business.system.vote.service.impl;

import com.business.system.vote.entity.Vote;
import com.business.system.vote.entity.VoteOption;
import com.business.system.vote.mapper.VoteOptionMapper;
import com.business.system.vote.mapper.VoteMapper;
import com.business.system.vote.service.IVoteService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 投票
 * @Author: jeecg-boot
 * @Date:   2020-05-13
 * @Version: V1.0
 */
@Service
public class VoteServiceImpl extends ServiceImpl<VoteMapper, Vote> implements IVoteService {

	@Autowired
	private VoteMapper voteMapper;
	@Autowired
	private VoteOptionMapper voteOptionMapper;
	
	@Override
	@Transactional
	public void saveMain(Vote vote, List<VoteOption> voteOptionList) {
		voteMapper.insert(vote);
		if(voteOptionList!=null && voteOptionList.size()>0) {
			for(VoteOption entity:voteOptionList) {
				//外键设置
				entity.setVoteId(vote.getId());
				voteOptionMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void updateMain(Vote vote,List<VoteOption> voteOptionList) {
		voteMapper.updateById(vote);
		
		//1.先删除子表数据
		voteOptionMapper.deleteByMainId(vote.getId());
		
		//2.子表数据重新插入
		if(voteOptionList!=null && voteOptionList.size()>0) {
			for(VoteOption entity:voteOptionList) {
				//外键设置
				entity.setVoteId(vote.getId());
				voteOptionMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void delMain(String id) {
		voteOptionMapper.deleteByMainId(id);
		voteMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			voteOptionMapper.deleteByMainId(id.toString());
			voteMapper.deleteById(id);
		}
	}
	
}
